package com.daykw.xiaohongshu.util;

import java.util.List;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;

public class ZKC {
	private static final String CONNECT_ADDR = Const.ZK_NODES;
	private static final int SESSION_TIMEOUT = 5000;
	private static Logger LOGGER = Logger.getLogger(ZKC.class);
	private static RetryPolicy policy = new ExponentialBackoffRetry(2000, 5);
	private static ZKC client;
	private static String path = "/node/xhs";
	public CuratorFramework curator;
	// 节点所在分组

	private ZKC() {
		try {
			curator = CuratorFrameworkFactory.builder().connectString(CONNECT_ADDR).sessionTimeoutMs(SESSION_TIMEOUT)
					.retryPolicy(policy).build();
			curator.start();
			if (curator.checkExists().forPath(path) == null) {
				curator.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);
			}
			LOGGER.info("zk 已连接:" + CONNECT_ADDR);
		} catch (Exception e) {
			LOGGER.error("", e);
		}

	}

	public List<String> getChildren() throws Exception {
		try {
			List<String> ret = curator.getChildren().forPath(path);

			return ret;
		} catch (Exception e) {
			LOGGER.error("", e);
			throw new Exception(e);
		}

	}

	public int getNodeIndex(String node) throws Exception {
		try {

			List<String> ret = curator.getChildren().forPath(path);
			for (int i = 0; i < ret.size(); i++) {
				if (node.equals(ret.get(i))) {
					return i;
				}
			}
			return 0;
		} catch (Exception e) {
			LOGGER.error("", e);
			throw new Exception(e);
		}

	}

	public synchronized static ZKC getZKClient() {
		if (client == null) {
			client = new ZKC();
		}
		return client;
	}

	public void doStart(String node) throws Exception {

		if (curator.checkExists().forPath(path + "/" + node) == null) {
			curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path + "/" + node);
			MyConnectionStateListener stateListener = new MyConnectionStateListener(path + "/" + node, "");
			curator.getConnectionStateListenable().addListener(stateListener);
		}
	}

	public static void main(String[] args) throws Exception {
		String sql = "SELECT * FROM t_article_task where status = 0 and mod(id,{size})={index} LIMIT 10;";
		if (sql.contains("{index}")) {
			System.out.println("1");
		}

		ZKC zkc = ZKC.getZKClient();
		String ip = Const.getLocalHostIp();
		zkc.doStart(ip);
		int s = zkc.getNodeIndex(ip);
		System.out.println(s);
	}

}
